package org.chen.listener;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.chen.common.model.DailyStats;
import org.chen.common.model.travel.StoreTravelOrder;
import org.chen.service.DailyStatsService;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;

@Component
@Slf4j
public class OrderRefundConsumer {
    private final ObjectMapper objectMapper;

    private final DailyStatsService dailyStatsService;

    public OrderRefundConsumer(ObjectMapper objectMapper,DailyStatsService dailyStatsService) {
        this.objectMapper = objectMapper;
        this.dailyStatsService = dailyStatsService;
    }

    @KafkaListener(topics = "order-refund", groupId = "order-refunding-group")
    public void listen(String message) {
        try {
            StoreTravelOrder order = objectMapper.readValue(message, StoreTravelOrder.class);
            processOrder(order);
        } catch (Exception e) {
            // 处理异常，例如记录日志
            log.error("Error processing order message", e);
        }
    }

    @Transactional
    public void processOrder(StoreTravelOrder order) {
        Date today = DateUtils.truncate(new Date(), Calendar.DATE);
        DailyStats dailyStats = dailyStatsService.findByStatDateForUpdate(today);

        if (dailyStats == null) {
            dailyStats = new DailyStats();
            dailyStats.setStatDate(today);
            dailyStats.setRefundAmount(dailyStats.getRefundAmount().add(order.getRefundPrice()));
            dailyStats.setCreatedAt(new Date());
            dailyStats.setUpdatedAt(new Date());
            dailyStatsService.save(dailyStats);
        } else {
            dailyStats.setRefundAmount(dailyStats.getRefundAmount().add(order.getRefundPrice()));
            dailyStats.setUpdatedAt(new Date());
            dailyStatsService.updateByIdWithVersion(dailyStats);
        }

        log.info("Updated daily stats for date: {}, new order count: {}, new total amount: {}",
                today, dailyStats.getOrderCount(), dailyStats.getRefundAmount());
    }
}
